package com.example.config;

import com.example.pojo.User;
import com.example.service.UserService;
import org.apache.shiro.authc.AuthenticationException;
import org.apache.shiro.authc.AuthenticationInfo;
import org.apache.shiro.authc.AuthenticationToken;
import org.apache.shiro.authc.SimpleAuthenticationInfo;
import org.apache.shiro.authz.AuthorizationInfo;
import org.apache.shiro.authz.SimpleAuthorizationInfo;
import org.apache.shiro.realm.AuthorizingRealm;
import org.apache.shiro.subject.PrincipalCollection;
import org.apache.shiro.util.SimpleByteSource;
import org.springframework.beans.factory.annotation.Autowired;

import java.util.List;


public class CustomerRealm extends AuthorizingRealm {

    @Autowired
    UserService userService;

    //认证操作
    @Override
    protected AuthenticationInfo doGetAuthenticationInfo(AuthenticationToken token) throws AuthenticationException {
        System.out.println("开始管理员认证操作...........");
        //（1）获得用户输入的账号：
        // principals:身份即主体的标识属性,可以是任何东西.如用户名,邮箱等.唯一即可.
        String username = (String) token.getPrincipal();
        System.out.println("principal:"+username);
        //（2）在 mysql中 进行验证用户输入的账号
        User user = userService.findUserByUserName(username);
        System.out.println("user:"+user);
        //（3）判断 mysql中是否有该用户
        if(user==null){
            return null;
        }else{
            //（4）mysql中有该用户，则调用 Shiro底层方法，比对密码
            AuthenticationInfo info= new SimpleAuthenticationInfo(
                    username, user.getAdmin_password(),
                    new SimpleByteSource("aaa"),"authRealm");
            System.out.println("info:"+info);
            return info;
        }
    }

    //授权
    @Override
    protected AuthorizationInfo doGetAuthorizationInfo(PrincipalCollection principals) {

        System.out.println("开始管理员授权操作...........");
        //从认证那里获取到用户对象User
        String userName = (String) principals.getPrimaryPrincipal();
        //获取当前用户的权限信息
        List<String> permssions = userService.getPermissions(userName);
        System.out.println(userName+"具备的权限是:"+permssions);

        //此方法需要一个AuthorizationInfo类型的返回值，因此返回一个它的实现类SimpleAuthorizationInfo
        //通过SimpleAuthorizationInfo里的addStringPermission()设置用户的权限
        SimpleAuthorizationInfo simpleAuthorizationInfo=new SimpleAuthorizationInfo();

        simpleAuthorizationInfo.addStringPermissions(permssions);

        return simpleAuthorizationInfo;
    }
}
